#include "tcp_connection.hpp"
#include "../utils/logger.hpp"
#include <unistd.h> // write

// 构造函数
TcpConnection::TcpConnection(int fd, const std::string& peer_address)
    : fd_(fd), peer_address_(peer_address), is_connected_(true) {
}

// 发送数据
void TcpConnection::send(const std::string& message) {
    if (!is_connected_) {
        Logger::warn("Attempted to send data on a closed connection");
        return;
    }
    ssize_t n = write(fd_, message.c_str(), message.size());
    if (n < 0) {
        Logger::error("Failed to send data to peer: {}", peer_address_);
        isConnected_ = false; // 标记连接为断开
    } else {
        Logger::info("Sent {} bytes to peer: {}", n, peer_address_);
    }
}

// 获取对端地址
std::string TcpConnection::getPeerAddress() const {
    return peer_address_;
}

// 判断连接是否有效
bool TcpConnection::connected() const {
    return is_connected_;
}